import 'package:flutter/material.dart';
import 'package:flutter_aliyun_nui/flutter_aliyun_nui.dart';

/// 错误处理示例
/// 展示如何使用NuiErrorType枚举进行类型化错误处理
class ErrorHandlingExample extends StatefulWidget {
  const ErrorHandlingExample({Key? key}) : super(key: key);

  @override
  State<ErrorHandlingExample> createState() => _ErrorHandlingExampleState();
}

class _ErrorHandlingExampleState extends State<ErrorHandlingExample> {
  String _errorMessage = '';
  String _errorDetails = '';
  Color _errorColor = Colors.red;

  @override
  void initState() {
    super.initState();
    _setupErrorHandling();
  }

  void _setupErrorHandling() {
    ALNui.setMethodCallHandler(
      errorHandler: _handleError,
    );
  }

  /// 类型化错误处理
  void _handleError(NuiError error) {
    setState(() {
      _errorMessage = error.userFriendlyMessage;
      _errorDetails = '错误码: ${error.errorCode}\n'
          '错误类型: ${error.errorType.name}\n'
          '详细描述: ${error.description}\n'
          '原始消息: ${error.errorMessage}';
    });

    // 根据错误类型进行不同的处理
    switch (error.errorType) {
      case NuiErrorType.tokenExpiredOrInvalid:
        _handleTokenError(error);
        break;
      case NuiErrorType.parameterInvalid:
        _handleParameterError(error);
        break;
      case NuiErrorType.tooManyRequests:
        _handleNetworkError(error);
        break;
      case NuiErrorType.invalidWavHeader:
      case NuiErrorType.tooLargeWavHeader:
        _handleAudioFormatError(error);
        break;
      case NuiErrorType.messageInvalid:
        _handleMessageError(error);
        break;
      case NuiErrorType.clientError:
        _handleClientError(error);
        break;
      default:
        _handleUnknownError(error);
        break;
    }
  }

  /// 处理Token错误
  void _handleTokenError(NuiError error) {
    setState(() {
      _errorColor = Colors.orange;
    });
    
    // 显示Token刷新对话框
    _showErrorDialog(
      title: 'Token错误',
      message: error.userFriendlyMessage,
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            _refreshToken();
          },
          child: const Text('刷新Token'),
        ),
      ],
    );
  }

  /// 处理参数错误
  void _handleParameterError(NuiError error) {
    setState(() {
      _errorColor = Colors.red;
    });
    
    _showErrorDialog(
      title: '参数错误',
      message: error.userFriendlyMessage,
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            _showConfigurationDialog();
          },
          child: const Text('检查配置'),
        ),
      ],
    );
  }

  /// 处理网络错误
  void _handleNetworkError(NuiError error) {
    setState(() {
      _errorColor = Colors.blue;
    });
    
    _showErrorDialog(
      title: '网络错误',
      message: error.userFriendlyMessage,
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            _retryAfterDelay();
          },
          child: const Text('稍后重试'),
        ),
      ],
    );
  }

  /// 处理音频格式错误
  void _handleAudioFormatError(NuiError error) {
    setState(() {
      _errorColor = Colors.purple;
    });
    
    _showErrorDialog(
      title: '音频格式错误',
      message: error.userFriendlyMessage,
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            _showAudioSettingsDialog();
          },
          child: const Text('检查音频设置'),
        ),
      ],
    );
  }

  /// 处理消息错误
  void _handleMessageError(NuiError error) {
    setState(() {
      _errorColor = Colors.amber;
    });
    
    _showErrorDialog(
      title: '消息格式错误',
      message: error.userFriendlyMessage,
    );
  }

  /// 处理客户端错误
  void _handleClientError(NuiError error) {
    setState(() {
      _errorColor = Colors.deepOrange;
    });
    
    _showErrorDialog(
      title: '客户端错误',
      message: error.userFriendlyMessage,
    );
  }

  /// 处理未知错误
  void _handleUnknownError(NuiError error) {
    setState(() {
      _errorColor = Colors.grey;
    });
    
    _showErrorDialog(
      title: '未知错误',
      message: error.errorMessage,
    );
  }

  /// 显示错误对话框
  void _showErrorDialog({
    required String title,
    required String message,
    List<Widget>? actions,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: actions ?? [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 刷新Token
  void _refreshToken() {
    // 实现Token刷新逻辑
    print('正在刷新Token...');
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('正在刷新Token...')),
    );
  }

  /// 显示配置对话框
  void _showConfigurationDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('配置检查'),
        content: const Text('请检查以下配置项：\n• AppKey\n• Token\n• DeviceId\n• URL'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 延迟重试
  void _retryAfterDelay() {
    print('将在5秒后重试...');
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('将在5秒后重试...')),
    );
    
    Future.delayed(const Duration(seconds: 5), () {
      print('开始重试...');
    });
  }

  /// 显示音频设置对话框
  void _showAudioSettingsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('音频设置检查'),
        content: const Text('请检查以下音频设置：\n• 格式: PCM/OPUS\n• 采样率: 8000/16000Hz\n• 声道: 单声道\n• 位深: 16位'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 模拟不同类型的错误
  void _simulateError(NuiErrorType errorType) {
    final error = NuiError.fromType(errorType);
    _handleError(error);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('错误处理示例'),
        backgroundColor: Colors.blue,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '错误类型测试',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            
            // 错误类型按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                _buildErrorButton('Token错误', NuiErrorType.tokenExpiredOrInvalid, Colors.orange),
                _buildErrorButton('参数错误', NuiErrorType.parameterInvalid, Colors.red),
                _buildErrorButton('请求过多', NuiErrorType.tooManyRequests, Colors.blue),
                _buildErrorButton('音频格式错误', NuiErrorType.invalidWavHeader, Colors.purple),
                _buildErrorButton('消息错误', NuiErrorType.messageInvalid, Colors.amber),
                _buildErrorButton('客户端错误', NuiErrorType.clientError, Colors.deepOrange),
                _buildErrorButton('未知错误', NuiErrorType.unknown, Colors.grey),
              ],
            ),
            
            const SizedBox(height: 24),
            const Divider(),
            const SizedBox(height: 16),
            
            // 错误信息显示
            const Text(
              '最近错误信息',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            
            if (_errorMessage.isNotEmpty) ...[
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: _errorColor.withOpacity(0.1),
                  border: Border.all(color: _errorColor),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '用户友好消息:',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: _errorColor,
                      ),
                    ),
                    Text(_errorMessage),
                    const SizedBox(height: 8),
                    Text(
                      '详细信息:',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: _errorColor,
                      ),
                    ),
                    Text(
                      _errorDetails,
                      style: const TextStyle(fontSize: 12),
                    ),
                  ],
                ),
              ),
            ] else ...[
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey.withOpacity(0.1),
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Text('点击上方按钮模拟不同类型的错误'),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildErrorButton(String label, NuiErrorType errorType, Color color) {
    return ElevatedButton(
      onPressed: () => _simulateError(errorType),
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        foregroundColor: Colors.white,
      ),
      child: Text(label),
    );
  }
}